package com.gitee.deeround.jdbchelper.resultSetExtractors;

import com.gitee.deeround.jdbchelper.exception.DbException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomListObjectResultSetExtractor<T> extends BaseResultSetExtractor implements ResultSetExtractor<List<T>> {

    private CustomApply<T> customApply;

    public CustomListObjectResultSetExtractor(CustomApply<T> customApply) {
        this.customApply = customApply;
    }

    @Override
    public List<T> extractData(ResultSet rs) throws SQLException, DataAccessException {
        List<T> list = new ArrayList<>();
        ResultSetMetaData md = rs.getMetaData();
        int columnCount = md.getColumnCount();

        try {
            Map<String, Object> map = new HashMap<>();
            while (rs.next()) {
                try {
                    for (int j = 0; j < columnCount; j++) {
                        String columnName = resolveColumnName(md.getColumnLabel(j + 1));
                        Object columnValue = resolveDataValue(rs.getObject(j + 1));
                        map.put(columnName.toLowerCase(), columnValue);
                    }
                    list.add(customApply.apply(map));
                } catch (Throwable e) {
                    throw new DbException("赋值异常：" + e.getMessage());
                }
            }
        } catch (Throwable e) {
            throw new DbException("赋值异常：" + e.getMessage());
        }

        return list;
    }
}
